import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Dispatch, ConnectState } from '@/models/connect';
import { Settings } from '@ant-design/pro-layout';
import { Spin, Modal } from 'antd';
// import style from './index.less';
import style from './index.less';
import Service from './service';
import { router } from 'umi';
import { stringify } from 'querystring';

interface Props {
  dispatch: Dispatch;
  settings: Settings;
  location: any;
}

const Login: React.FC<Props> = props => {
  const { dispatch, settings, location: { query } } = props;

  const service = new Service('');
  const [username, setUsername] = useState<string>('');
  const [password, setPassword] = useState<string>('');
  const [expires, setExpires] = useState<number>(3600000);
  const [isReady, setIsReady] = useState(false);

  const [captcha, setCaptcha] = useState<string>('');
  const [captchaImg, setCaptchaImg] = useState<string>('');
  const [code, setCode] = useState<string>("");
  const [enable, setEnable] = useState<boolean>(false);
  const [showPassword, setShowPassword] = useState<boolean>(false);
  const [visible, setVisible] = useState(false);
  const [flag, setFlag] = useState(false);
  const [down, setDown] = useState(false);
  const [downX, setDownX] = useState(0);
  const [btnleft, setBtnleft] = useState<string>(0 + 'px');
  const [bgwidth, setBgwidth] = useState<string>(0 + 'px');
  const [text, setText] = useState<string>('拖动滑块验证');
  const [textcolor, setTextcolor] = useState<string>('');
  const handleOk = () => {
    setVisible(false)
  }
  const handleCancel = () => {
    setVisible(false)
  }
  const handClose = () => {
    setBtnleft(0 + "px");
    setBgwidth(0 + "px");
    setText("拖动滑块验证")
    setFlag(false)
  }
  const mousedown = () => {
    // console.log(event);
    setDown(true)
    setDownX(event.clientX)
  }
  const move = () => {
    if (down) {
      var moveX = event.clientX - downX;
      // console.log(moveX);
      if (moveX > -2) {
        setBtnleft(moveX + "px");//将移动值赋值给滑块
        setBgwidth(moveX + 40 + "px");//背景
        if (moveX >= (260)) {//包含原始宽度内边距边框，不包含外边框
          //拖到头，验证成功
          setFlag(true)
          setText("验证成功");
          setTextcolor("white");
          setDown(false)

          dispatch({
            type: 'login/login',
            payload: {
              username,
              password,
              expires,
              tokenType: 'default',
              verifyKey: captcha,
              verifyCode: code,
              bindCode: query?.code
            },
            callback: () => { getCodeImg() }
          });

          //事件清除
          // btn.onmousedown=null;
          // btn.onmousemove=null;
        }
      }
    }
  }
  const mouseup = () => {
    setDown(false)
    if (flag == false) {
      setBtnleft(0 + "px");//将移动值赋值给滑块
      setBgwidth(0 + "px");//背景
    }
  }

  const handleSubmit = () => {
    setVisible(true)

    // let user = localStorage.getItem('user-detail');
    // console.log('user', user)
    // router.replace('/consumer/page')
  };

  const handlePassword = () => {
    setShowPassword(!showPassword)
  };

  const getCodeImg = () => {
    if (enable) {
      service.getCaptcha().subscribe((resp) => {
        setCaptcha(resp.key);
        setCaptchaImg(resp.base64);
      });
    }
  }

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'settings/fetchConfig',
        callback: () => {
          const title = document.getElementById('sys-title');
          const icon = document.getElementById('title-icon');
          if (title && settings.title) {
            title.textContent = settings.title;
          }
          if (icon && settings.titleIcon) {
            icon.href = settings.titleIcon;
          }
          setIsReady(true);
        }
      });
    }

    //判断是否开启验证码
    service.captchaConfig().subscribe((resp) => {
      if (resp) {
        setEnable(resp.enabled)
        if (resp.enabled) {
          //获取验证码
          service.getCaptcha().subscribe((resp) => {
            setCaptcha(resp.key);
            setCaptchaImg(resp.base64);
          });
          // getCodeImg();
        } else {
          //未开启验证码
        }
      }
    });



  }, [settings.title]);


  const renderLogin = () => (
    <div className={style.login} onMouseMove={() => { move() }} onMouseUp={() => mouseup()}>
      <div className={style.png}></div>
      {/* <div className={style.bg1} />
      <div className={style.gyl}>
        物联网平台
        <div className={style.gy2}>MQTT TCP CoAP HTTP , 多消息协议适配 , 可视化规则引擎
        </div>
      </div> */}
      {/* style={{ height: enable ? '387px' : '330px' }} */}
      <div className={style.box}>
        <div className={style.box1} >
          <div className={style.title}>灯杆健康监测系统</div>
          {/* <div className={style.slogan}>搭建工业互联网设备数据底座</div> */}
          <div className={enable ? style.name : style.nameen}>用户名</div>
          <div className={style.item}>
            <input
              onChange={e => setUsername(e.target.value)}
              value={username}
              type="text"
              placeholder="请输入用户名"
            />

          </div>
          <div className={enable ? style.psd : style.psden}>登录密码</div>
          <div className={style.item} onKeyUp={e => { if (e.keyCode === 13 && !enable) { handleSubmit(); } }}>
            <input
              onChange={e => setPassword(e.target.value)}
              value={password}
              type={showPassword ? 'text' : 'password'}
              placeholder="请输入密码"
            />
            {showPassword ? <div className={style.search_img} onClick={() => { handlePassword(); }}></div>
              : <div className={style.search_imgbk} onClick={() => { handlePassword(); }}></div>}
          </div>

          {enable ? <div className={style.enable}>验证码</div> : <div></div>}
          {
            enable ? <div className={style.auth_class}><div className={style.item_auth}>
              <div className={style.userLabel_auth}></div>
              <input onKeyUp={e => { if (e.keyCode === 13) { handleSubmit(); } }}
                style={{ borderStyle: 'none none none none' }}
                onChange={e => setCode(e.target.value)}
                value={code}
                type="text"
                placeholder="请输入验证码"
              /></div>
              <div className={style.code} onClick={() => { getCodeImg(); }}><img src={captchaImg} className={style.code_img} /></div>
            </div> : <div></div>
          }

          <div className={style.wjpsd}>忘记密码</div>

          <input
            onClick={() => {
              handleSubmit();
            }}
            className={enable ? style.btn : style.btnen}
            type="button"
            name="登 录"
            value="登 录"
          />
        </div>
      </div>
      <div className={style.records}>
        {/* 巨霸 */}
        {/* <a href="https://beian.miit.gov.cn" target="view_window">豫ICP备2021025005号-1</a> */}
        {/* 飞虹 */}
        {/* <a href="https://beian.miit.gov.cn" target="view_window">豫ICP备07500823号</a> */}
        {/* 演示 */}
        {/* <a href="https://beian.miit.gov.cn" target="view_window">豫ICP备18011131号-2</a> */}
        {/* 演示现在 */}
        <a href="https://beian.miit.gov.cn" target="view_window" style={{ color: "#fff" }}>豫ICP备18011131号-2</a>
      </div>
      <Modal
        visible={visible}
        title={'安全验证'}
        onOk={handleOk}
        onCancel={handleCancel}
        afterClose={handClose}
        footer={null}
      >
        <div className={style.boxx} >
          <div>
            <div className={style.btn} onMouseDown={() => { mousedown() }}
              style={{ left: btnleft }}
            >
              <div></div>
            </div>
          </div>
          <p className={style.text} style={{ color: textcolor }}>{text}</p>
          <div className={style.bg} style={{ width: bgwidth }} ></div>
        </div>
      </Modal>
    </div>
  )
  return isReady ? renderLogin() : <Spin spinning={isReady} />;
};
export default connect(({ login, loading, settings }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
  settings
}))(Login);
